﻿const ready = fn => document.readyState !== 'loading' ? fn() : document.addEventListener('DOMContentLoaded', fn);
ready(async () => {
   
    await clickBannerPopupDemoForm();
});


addFavIcon('https://www.salary.com/favicon.ico');

function addFavIcon(href) {
    const link = document.createElement('link');
    link.rel = 'icon';
    link.type = 'image/svg+xml';
    link.href = href;
    const existingLink = document.querySelector('head link[rel="icon"]');
    if (existingLink) {
        existingLink.parentElement.replaceChild(link, existingLink);
    } else {
        document.getElementsByTagName('head')[0].appendChild(link);
    }
}
async function getFormHtml(apiUrl, jsonData) {

    const _settings = {
        method: 'POST',
        body: JSON.stringify(jsonData),
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        }
    };
    const response = await fetch(apiUrl, _settings);
    if (!response.ok) throw new Error(response.message);
    const html = await response.text();
    return html;
}

function loadScript(location, url, id, callback, defer) {
    const script = document.querySelector(`#${id}`);
    if (script) script.remove();
    const $head = document.querySelector('head');
    const $body = document.querySelector('body');
    const $script = document.createElement('script');
    $script.id = id;
    if (url) $script.src = url;
    if (defer && $script.src) $script.defer = defer;
    if (location === 'header') {
        $head.append($script);
    } else if (location === 'footer') {
        $body.append($script);
    }
    $script.onload = callback;
    return $script;
}

function loadCSS(href, callback) {
    if (!document.querySelector(`head> link[href="${href}"]`)) {
        const link = document.createElement('link');
        link.setAttribute('rel', 'stylesheet');
        link.setAttribute('href', href);
        if (typeof callback === 'function') {
            link.onload = (e) => callback(e.type);
            link.onerror = (e) => callback(e.type);
        }
        document.head.appendChild(link);
    } else if (typeof callback === 'function') {
        callback('noop');
    }
}

async function clickBannerPopupDemoForm() {
    const popupDemoForm = async (productTypeText) => {
        let suffix = window.screen.width >= 992 ? "d" : 'm';
        try {
            let strLeadSource;
            let partialFileName;
            productTypeText = productTypeText.toLowerCase();
            switch (productTypeText) {
                case "jsm":
                    strLeadSource = `c${suffix}_b2b_click_resources_howto_skill_inquiry`;
                    partialFileName = "jobskill";
                    break;
                case "iq":
                    strLeadSource = `c${suffix}_b2b_click_resources_howto_iq_inquiry`;
                    partialFileName = "iq";
                    break;
                case "rewards":
                case "cp":
                    strLeadSource = `c${suffix}_b2b_click_resources_howto_reward_inquiry`;
                    partialFileName = "cp";
                    break;
                case "ja":
                    strLeadSource = `c${suffix}_b2b_click_resources_howto_jdinquiry`;
                    partialFileName = "jd";
                    break;
                case "ipas":
                case "compdata":
                    strLeadSource = `c${suffix}_b2b_click_resources_howto_survey_inquiry`;
                    partialFileName = "survey";
                    break;
                case "pe":
                    strLeadSource = `c${suffix}_b2b_click_resources_howto_petrial_inquiry`;
                    partialFileName = "pe";
                    break;
                case "ca":
                case "camd":
                default:
                    strLeadSource = `c${suffix}_b2b_click_resources_howto_pricinginquiry`;
                    partialFileName = "ca";
                    break;
            }
            let deomFormModalUrl = `/business/search/BusinessSearch/SalAjxGetPopup${partialFileName}DemoFormHtml`;
            let demoFormJS = `/business/search/UtilityScripts/Salary/Seou_Share_Popup${partialFileName}DemoForm.js`;
            let demoFormCSS = `/business/search/Styles/ElementStyles/CSS/Seos_Share_Popup${partialFileName}DemoForm.css`;
            let strRequestPageUrl = window.location.pathname;
            let strPageCategoryType = "How-to";
            let strProductTypeNum = ProductType[Object.keys(ProductType).find(k => k.toLowerCase() === productTypeText.toLowerCase())];
            let params = { strRequestPageUrl, strLeadSource, strPageCategoryType, strProductTypeNum };
            popupType = DemoFormPopupType.Click;
            B2BPopupProgress.ClickPopupStart = true;
            let demoFormModal = await getFormHtml(deomFormModalUrl, params);
            loadScript('footer', demoFormJS, `${productTypeText}_${strProductTypeNum}`, async () => {
                loadCSS(`${demoFormCSS}`);
                let demoForm = document.querySelector("[id^=sal-][id$=form-container]");
                if (demoForm !== null) { demoForm.remove(); }
                document.body.insertAdjacentHTML('beforeEnd', demoFormModal);
                B2BPopupProgress.ClickPopupEnd = true;
                B2BPopupProgress.ClickPopupStart = false;
                SalPopupDemoFormInit();
            });
        } catch (err) {
            throw new Error(`faild to popup ${partialFileName}`);
        }
    };

    const allCTAEles = document.querySelectorAll(`img[class^="articles_how_to_cta_"]`);
    [...allCTAEles].forEach(btnEle => {
        btnEle.addEventListener('click', async (e) => {
            e.preventDefault();
            const productTypeText = btnEle.className.split(' ')[0].split('_').slice(-1)[0];
            await popupDemoForm(productTypeText);
        });
    });
}


